import wx
import wx.lib.agw.aui as aui
import firebrick

FID="rwb.core.clipboard"

class ClipboardPlugin(firebrick.Plugin):
    '''Creates a window for tracking system clipboard contents'''

    def __init__(self, app):
        super(ClipboardPlugin, self).__init__(_id=FID,
                            url=None, version="0.1", 
                            name="Clipboard",
                            default_settings = {})
        
    def enable(self):
        self.app.Register(ClipboardPanel)
        self.active = True

    def disable(self):
        self.active = False
        self.app.Unregister(ClipboardPanel)
        # this should also destroy the panel and
        # stop the timer. 

class ClipboardPanel(firebrick.BasePanel):
    name = "Clipboard"
    _id = FID

    def __init__(self, parent):
        super(ClipboardPanel, self).__init__(parent)
        parent.auimgr.AddPane(self, aui.AuiPaneInfo().Right().
                              CaptionVisible(True).Caption(self.name).
                              BestSize(wx.Size(250,200)).Name(FID).Show(False))

        # instead of a listbox, I need something that can have
        # zebra stripes, or some way to delineate one item from the
        # next...
        self.list = wx.ListBox(self, wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.list, 1, wx.EXPAND)
        self.SetSizerAndFit(sizer)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer)
        self.list.Bind(wx.EVT_LISTBOX, self.OnListbox)

        self._update()

        # every couple of seconds is Good Enough. Under normal use
        # people won't be pasting data every second
        self.timer.Start(2000)

    def OnListbox(self, event):
        '''Copy the selected item to the clipboard'''
        try:
            if event.IsSelection():
                # without the above check, when the window
                # goes away we get an event (deselection?),
                # and the following code throws a Gtk-CRITICAL 
                # assertion. 
                index = event.GetSelection()
                data = wx.TextDataObject()
                data.SetText(self.list.GetString(index))
                wx.TheClipboard.Open()
                wx.TheClipboard.SetData(data)
                wx.TheClipboard.Close()
        except:
            # the world shouldn't end if we can't do what
            # we want to do. <shrug>
            self.app.log.debug("unable to copy data to clipboard: %s" % str(e))

    def OnTimer(self, event):
        '''Periodically check the clipboard and save the contents'''
        try:
            self._update()
        except Exception, e:
            self.app.log.debug("unable to fetch data from clipboard: %s" % str(e))


    def _update(self):
        '''Poll the clipboard and update the display'''
        if not wx.TheClipboard.IsOpened():
            wx.TheClipboard.Open()
            data = wx.TextDataObject()
            success = wx.TheClipboard.GetData(data)
            wx.TheClipboard.Close()
            text = data.GetText()
            if self.list.GetCount() < 1:
                index = self.list.Append(text)
            else:
                index = self.list.FindString(text)
                if index < 0:
                    index = self.list.Append(text)
            current_selection = self.list.GetSelection()
            if current_selection != index:
                self.list.Select(index)
            self.list.Update()
